package com.paireach.szwolaiyun.newFragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.paireach.szwolaiyun.R;
import com.paireach.szwolaiyun.service.LocationUploadService;
import com.paireach.szwolaiyun.sz_common_widget.adapter.AppBaseAdapter;
import com.paireach.szwolaiyun.sz_common_widget.adapter.ViewHolder;
import com.paireach.szwolaiyun.sz_common_widget.fragment.BaseFragment;
import com.paireach.szwolaiyun.sz_util.SharedPreferencesUtil;
import com.paireach.szwolaiyun.sz_util.ToastUtil;
import com.paireach.szwolaiyun.util.BaiDuSimpleLocationHelp;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.List;

import szwolaiyun.paireach.com.szwolaizhuang.model.business.DriveOrder;
import szwolaiyun.paireach.com.szwolaizhuang.model.business.Goods;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.AppEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpErrorEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpSuccessEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.requestTag.RequestTag;
import szwolaiyun.paireach.com.szwolaizhuang.net.WayBillRequest;
import szwolaiyun.paireach.com.szwolaizhuang.net.json.JsonPaser;

/**
 * A中的fragment，运单详情，可以进行装货签到（已接单）或者是接收单（未接单），考虑加上收货签到功能
 * Created by Administrator on 2016/7/4.
 * 270：准备运输
 * 232：送货在途
 * 244：已签收
 */
public class OrderDetailsFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = "OrderDetailsFragment";
    private View rootView;
    private Button btn_acceptOrder;
    private ListView listView;
    private ListAdapter adapter;
    private BaiDuSimpleLocationHelp baiDuSimpleLocationHelp;
    private MyHandler handler;
//    private boolean state;


    private DriveOrder order;
    //    private static Context  context = getContext();

    //    public static OrderDetailsFragment getInstance(boolean state, DriveOrder order) {
//        OrderDetailsFragment fragment = new OrderDetailsFragment();
//        Bundle bundle = new Bundle();
//        bundle.putBoolean("state", state);
//        bundle.putSerializable("DriveOrder", order);
//        fragment.setArguments(bundle);
//        return fragment;
//    }
    public static OrderDetailsFragment getInstance(DriveOrder order) {
        OrderDetailsFragment fragment = new OrderDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("DriveOrder", order);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();
        if (bundle != null) {
//            state = bundle.getBoolean("state");
            order = (DriveOrder) bundle.getSerializable("DriveOrder");
        }
        adapter = new ListAdapter(getActivity());
        baiDuSimpleLocationHelp = new BaiDuSimpleLocationHelp();
        handler = new MyHandler(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_details, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        setupView();
    }


    @Override
    public void onResume() {
        super.onResume();
        showProgressDialog();
        new WayBillRequest().getOrderGoodsDetail(order.getOrderNo());//tag: GET_WAY_BILL_DETAIL_GOODS
    }

    private void setupView() {
        ((TextView) rootView.findViewById(R.id.tv_home_ordercode)).setText(order.getOrderNo());
        ((TextView) rootView.findViewById(R.id.tv_ordertime)).setText(order.getPlaceTime());
        ((TextView) rootView.findViewById(R.id.tv_originname)).setText(order.getCustomerName());
//        ((TextView) rootView.findViewById(R.id.tv_origin_address)).setText(order.getStartPlaceDetailAddress());
        ((TextView) rootView.findViewById(R.id.tv_endname)).setText(order.getSupplierName());
//        ((TextView) rootView.findViewById(R.id.tv_end_address)).setText(order.getEndPlaceDetailAddress());
    }

    private void initView() {
        btn_acceptOrder = (Button) rootView.findViewById(R.id.btn_acceptOrder);
        btn_acceptOrder.setOnClickListener(this);
        btn_acceptOrder.setText("开始运输");
        listView = (ListView) rootView.findViewById(R.id.lv_orderdetail);
        listView.setAdapter(adapter);
        if (order.getOrderState().equals("准备运输")) {
            btn_acceptOrder.setText("开始运输");
        } else {
            btn_acceptOrder.setText("签收");
        }
    }

    @Override
    public void onClick(View v) {
        if (v == btn_acceptOrder) {
//            if (btn_acceptOrder.getText().equals("开始运输")) {
////                acceptWayBill();
//                //增加开始运输按钮
//                showProgressDialog();
//                new WayBillRequest().StartTransPost(order.getOrderNo());
//            } else {
//                //签收，给服务器发送一个请求，参数：运单号 + 精度 + 纬度  。。。
//                sign();
//            }
            sign();
        }
    }


    /**
     * 签到方法
     */
    private void sign() {
        showProgressDialog();
        baiDuSimpleLocationHelp.startGetLocation(getActivity(), handler, null);
    }

    /**
     * 接收运单/司机接单
     */
    private void acceptWayBill() {
        showProgressDialog();
        new WayBillRequest().driverAcceptOrder(order.getOrderNo());
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
//        if (event.getTag().equals("driver_accept_order")) {
//            showToast(event.getExtraInfo());
//            if (event.getCode() == 0) {
//                getActivity().finish();
//            }
//        } else
        if (event.getTag().equals("order_detail_goods")) {//获取运单详情成功
            if (event.getCode() == 0) {
                List<Goods> goodsList = (List<Goods>) event.getObj1();
                adapter.setListAndRefresh(goodsList);
            }
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.DRIVER_ACCEPT_ORDER ||
                event.getRequestTag() == RequestTag.SIGN ||
                event.getRequestTag() == RequestTag.GET_WAY_BILL_DETAIL_GOODS) {
            dismissProgressDialog();
            showToast(event.getErrorMessage());
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
//        if (event.getRequestTag() == RequestTag.DRIVER_ACCEPT_ORDER) {
//            //司机接单
//            dismissProgressDialog();
//            JsonPaser.parseDriverAcceptOrder(event.getJson());
//        } else
        if (event.getRequestTag() == RequestTag.SIGN) {
            //签到
            dismissProgressDialog();
            // 判断确实是签到成功后，finish这个界面，通過通知來點擊進別的界面，這個界面的任務就完成了
//            JsonPaser.parseSignInfo2(event.getJson());
            getActivity().finish();
        } else if (event.getRequestTag() == RequestTag.GET_WAY_BILL_DETAIL_GOODS) {//运单详情
            dismissProgressDialog();
            //获取订单中的商品信息
            JsonPaser.parseOrderDetailGoods(event.getJson());
        }
    }

    private class ListAdapter extends AppBaseAdapter {

        public ListAdapter(Context mContext) {
            super(mContext);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = ViewHolder.get(getContext(), convertView, parent, R.layout.item_order_detail_goods, position);
            Goods goods = (Goods) getItem(position);
            ((TextView) viewHolder.getView(R.id.txt1)).setText(goods.getGoodsCode());
            ((TextView) viewHolder.getView(R.id.txt2)).setText(goods.getGoodsName());
            ((TextView) viewHolder.getView(R.id.txt3)).setText(goods.getChargeQty() + goods.getChargeUnit());//22.93 + 吨
            ((TextView) viewHolder.getView(R.id.txt4)).setText(goods.getQty() + goods.getUnit());//2231+箱
            return viewHolder.getConvertView();
        }
    }

    // private static class MyHandler extends Handler {
    private class MyHandler extends Handler {

        private WeakReference<OrderDetailsFragment> mm;

        public MyHandler(OrderDetailsFragment service) {
            mm = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OrderDetailsFragment service = mm.get();
            if (service != null) {
                switch (msg.what) {
                    case BaiDuSimpleLocationHelp.getLocationSucceed:
                        BDLocation location = (BDLocation) msg.obj;
                        //tag:RequestTag.SIGN
                        new WayBillRequest().sign(
                                service.order.getOrderNo(),
                                SharedPreferencesUtil.getValue(getContext(), SharedPreferencesUtil.USER_PHONE),
                                location.getLatitude(),
                                location.getLongitude(),
                                String.valueOf(location.getSpeed()),
                                String.valueOf(location.getDirection()),
                                String.valueOf(location.getAddress().address),
                                location.getProvince(),
                                location.getCity(),
                                location.getDistrict(),
                                "",
                                'C');
                        Log.d(TAG, "location.getAddress().address = " + location.getAddress().address);
                        break;
                }
            }
        }
    }
}
